import pymysql
from flask import Blueprint, jsonify, request
from ..extensions import redis_conn
from ..database import db_connection, get_mongo_client, mongo_collection
from ..utils import device_required, validate_user_id
from ..config import Config
from datetime import datetime

general_bp = Blueprint('general', __name__)

@general_bp.route('/v1/health', methods=['GET'])
def health_check():
    try:
        services = []
        errors = []
        
        # Redis健康检查
        try:
            if redis_conn.redis.ping():
                services.append("redis")
            else:
                errors.append("Redis connection failed")
        except Exception as e:
            errors.append(f"Redis error: {str(e)}")
        
        # MySQL健康检查
        try:
            with db_connection() as conn:
                with conn.cursor() as cursor:
                    cursor.execute("SELECT 1")
                    if cursor.fetchone():
                        services.append("mysql")
                    else:
                        errors.append("MySQL check failed")
        except Exception as e:
            errors.append(f"MySQL error: {str(e)}")
        
        # MongoDB健康检查
        try:
            client = get_mongo_client()
            info = client.server_info()
            if info:
                services.append("mongodb")
            else:
                errors.append("MongoDB check failed")
        except Exception as e:
            errors.append(f"MongoDB error: {str(e)}")
        
        if errors:
            return jsonify(
                code=50301,
                message="Service partially available",
                services=services,
                errors=errors
            ), 503 if len(services) == 0 else 207
        
        return jsonify(status="OK", services=services), 200
    except Exception as e:
        return jsonify(
            code=50301,
            message="Service unavailable",
            error=str(e)
        ), 503

@general_bp.route('/v1/get/devicestate', methods=['GET'])
def get_device_state():
    """
    获取设备状态接口
    请求示例：/api/v1/get/devicestate?device_id=CQUCHX0503001
    """
    try:
        # 获取设备ID参数
        device_id = request.args.get('device_id')
        if not device_id:
            return jsonify(
                code=40002,
                message="缺少必要参数: device_id"
            ), 400

        # 从MongoDB查询最新的设备状态
        with mongo_collection(Config.MONGODB_COLLECTIONS["device_status"]) as collection:
            # 按时间戳降序排序，获取最新的状态
            status = collection.find_one(
                {"device_id": device_id},
                sort=[("timestamp", -1)]
            )
            
            if not status:
                return jsonify(code=40401, message="设备状态不存在"), 404
            
            # 从MySQL获取用户ID
            user_id = None
            with db_connection() as conn:
                with conn.cursor() as cursor:
                    cursor.execute("SELECT user_id, is_activated FROM device WHERE device_id = %s", (device_id,))
                    device_data = cursor.fetchone()
                    if device_data:
                        user_id = device_data['user_id']
                        is_activated = device_data['is_activated']
            
            # 确定设备激活状态
            activation_status = "ACTIVATED" if is_activated else "INACTIVATED"
            
            # 获取连接状态
            connection_status = status.get("connection_status", "UNKNOWN")
            
            # 构造响应数据结构
            response = {
                "code": 0,
                "user_id": user_id,
                "device_id": device_id,
                "connection_status": connection_status,
                "activation_status": activation_status,
                "timestamp": status["timestamp"].isoformat() if isinstance(status["timestamp"], datetime) else status["timestamp"],
                "received_at": status.get("received_at", "").isoformat() if isinstance(status.get("received_at"), datetime) else status.get("received_at", ""),
                "Power": {
                    "state": status["power"]["state"],
                    "battery_level": status["power"]["battery_level"],
                    "isCharging": status["power"]["charging_state"]
                },
                "Net": {
                    "Wifi_state": status["network"]["wifi_state"],
                    "net_delay": status["network"]["net_delay"]
                },
                "Audio": {
                    "effect": status["audio"]["effect"],
                    "mode": status["audio"]["mode"]
                }
            }

            return jsonify(response), 200

    except pymysql.MySQLError as e:
        print(f"[DATABASE ERROR] {str(e)}")  # 添加详细错误日志
        return jsonify(
            code=50002,
            message="数据库错误",
            error=str(e)
        ), 500
    except Exception as e:
        print(f"[SYSTEM ERROR] {str(e)}")  # 记录未捕获的异常
        return jsonify(
            code=50000,
            message="服务器内部错误",
            error=str(e)  # 返回具体错误信息
        ), 500

@general_bp.route('/v1/music_preferences', methods=['GET'])
def get_music_preferences():
    """
    获取用户音乐偏好接口
    请求示例：/api/v1/music_preferences?user_id=4&year=2025&month=4&day=
    
    参数说明：
    - user_id: 用户ID (必填)
    - year: 年份 (选填，默认当前年)
    - month: 月份 (选填，如果提供则返回月度数据)
    - day: 日期 (选填，如果提供则返回日度数据)
    
    根据参数组合返回不同粒度的数据:
    - 只有year: 返回年度数据
    - year+month: 返回月度数据
    - year+month+day: 返回日度数据
    
    注意: 此接口为只读查询操作，不记录操作日志到MongoDB
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        year = request.args.get('year')
        month = request.args.get('month')
        day = request.args.get('day')
        
        # 参数验证
        if not user_id:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message="缺少必要参数: user_id"
            ), 400
            
        if not validate_user_id(user_id):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
        
        # 转换用户ID为整数类型
        user_id_int = int(user_id)
        
        # 确定查询类型和构建查询条件
        query_type = "yearly"
        query_condition = {}
        
        # 添加用户ID条件 - 同时支持字符串和整数类型
        query_condition["$or"] = [{"user_id": user_id_int}, {"user_id": user_id}]
        
        # 设置当前年份作为默认值
        current_year = datetime.now().year
        year_int = current_year
        
        if year:
            try:
                year_int = int(year)
                query_condition["year"] = year_int
            except ValueError:
                return jsonify(code=40010, message="年份必须为整数"), 400
        else:
            # 如果未提供年份，使用当前年份
            query_condition["year"] = current_year
        
        if month:
            query_type = "monthly"
            try:
                month_int = int(month)
                if month_int < 1 or month_int > 12:
                    return jsonify(code=40010, message="月份必须在1-12之间"), 400
                query_condition["month"] = month_int
            except ValueError:
                return jsonify(code=40010, message="月份必须为整数"), 400
        
        if day and month:  # 日期查询需要同时有月份
            query_type = "daily"
            try:
                day_int = int(day)
                if day_int < 1 or day_int > 31:
                    return jsonify(code=40010, message="日期必须在1-31之间"), 400
                query_condition["day"] = day_int
            except ValueError:
                return jsonify(code=40010, message="日期必须为整数"), 400
        
        # 根据查询类型选择集合
        collection_name = ""
        if query_type == "yearly":
            collection_name = Config.MONGODB_COLLECTIONS["yearly_preferences"]
        elif query_type == "monthly":
            collection_name = Config.MONGODB_COLLECTIONS["monthly_preferences"]
        else:  # daily
            collection_name = Config.MONGODB_COLLECTIONS["daily_preferences"]
        
        # 记录查询条件和集合名称，便于调试
        print(f"[DEBUG] 查询条件: {query_condition}, 集合: {collection_name}")
        
        # 从MongoDB获取用户偏好数据
        preferences = []
        with mongo_collection(collection_name) as collection:
            # 查询数据
            preferences = list(collection.find(query_condition))
            
            # 如果没有找到数据，尝试使用daily_preferences集合
            if not preferences and collection_name != Config.MONGODB_COLLECTIONS["daily_preferences"]:
                print(f"[DEBUG] 在{collection_name}中未找到数据，尝试从daily_preferences中聚合")
                
                # 构建日期条件
                date_condition = {"$or": [{"user_id": user_id_int}, {"user_id": user_id}]}
                
                if year:
                    if query_type == "yearly":
                        # 年度查询：匹配整年
                        date_condition["date"] = {"$regex": f"^{year_int}"}
                    elif query_type == "monthly":
                        # 月度查询：匹配年月
                        month_str = f"{month_int:02d}"
                        date_condition["date"] = {"$regex": f"^{year_int}-{month_str}"}
                
                with mongo_collection(Config.MONGODB_COLLECTIONS["daily_preferences"]) as daily_collection:
                    daily_records = list(daily_collection.find(date_condition))
                    
                    if daily_records:
                        # 手动聚合数据
                        aggregated_data = {}
                        
                        for record in daily_records:
                            # 处理风格偏好
                            if "style_preferences" in record:
                                if "style_preferences" not in aggregated_data:
                                    aggregated_data["style_preferences"] = {}
                                
                                for style, minutes in record["style_preferences"].items():
                                    if style in aggregated_data["style_preferences"]:
                                        aggregated_data["style_preferences"][style] += minutes
                                    else:
                                        aggregated_data["style_preferences"][style] = minutes
                            
                            # 处理时段偏好
                            if "period_preferences" in record:
                                if "period_preferences" not in aggregated_data:
                                    aggregated_data["period_preferences"] = {}
                                
                                for period, minutes in record["period_preferences"].items():
                                    if period in aggregated_data["period_preferences"]:
                                        aggregated_data["period_preferences"][period] += minutes
                                    else:
                                        aggregated_data["period_preferences"][period] = minutes
                        
                        # 创建聚合记录
                        if aggregated_data:
                            aggregated_record = {
                                "user_id": user_id_int,
                                "timestamp": datetime.now(),
                                "total_duration": sum(minutes for minutes in aggregated_data.get("style_preferences", {}).values())
                            }
                            
                            # 添加年月日信息
                            if year:
                                aggregated_record["year"] = year_int
                            if month:
                                aggregated_record["month"] = month_int
                            if day:
                                aggregated_record["day"] = day_int
                            
                            # 合并聚合数据
                            aggregated_record.update(aggregated_data)
                            
                            preferences = [aggregated_record]
        
        # 如果仍然没有数据，返回空结果
        if not preferences:
            return jsonify({
                "code": 0,
                "message": "未找到用户偏好数据",
                "user_id": user_id_int,
                "query_type": query_type,
                "data": []
            }), 200
        
        for pref in preferences:
            if "_id" in pref:
                del pref["_id"]
            
            # 格式化时间戳
            if "timestamp" in pref and isinstance(pref["timestamp"], datetime):
                pref["timestamp"] = pref["timestamp"].isoformat()
        
        # 构建响应
        response = {
            "code": 0,
            "message": "获取用户偏好数据成功",
            "user_id": user_id_int,
            "query_type": query_type,
            "data": preferences
        }
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取用户偏好异常: {str(e)}")
        import traceback
        traceback.print_exc()  # 打印完整堆栈跟踪
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@general_bp.route('/v1/listening_duration', methods=['GET'])
def get_listening_duration():
    """
    获取用户听歌时长接口
    请求示例：/api/v1/listening_duration?user_id=4&year=2025&month=4&day=
    
    参数说明：
    - user_id: 用户ID (必填)
    - year: 年份 (选填，默认当前年)
    - month: 月份 (选填，如果提供则返回月度数据)
    - day: 日期 (选填，如果提供则返回日度数据)
    
    根据参数组合返回不同粒度的数据:
    - 只有year: 返回年度数据
    - year+month: 返回月度数据
    - year+month+day: 返回日度数据
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        year = request.args.get('year')
        month = request.args.get('month')
        day = request.args.get('day')
        
        # 参数验证
        if not user_id:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message="缺少必要参数: user_id"
            ), 400
            
        if not validate_user_id(user_id):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
        
        # 转换用户ID为整数类型
        user_id_int = int(user_id)
        
        # 确定查询类型和构建查询条件
        query_type = "yearly"
        query_condition = {}
        
        # 添加用户ID条件 - 同时支持字符串和整数类型
        query_condition["$or"] = [{"user_id": user_id_int}, {"user_id": user_id}]
        
        # 设置当前年份作为默认值
        current_year = datetime.now().year
        year_int = current_year
        
        if year:
            try:
                year_int = int(year)
                query_condition["year"] = year_int
            except ValueError:
                return jsonify(code=40010, message="年份必须为整数"), 400
        else:
            # 如果未提供年份，使用当前年份
            query_condition["year"] = current_year
        
        if month:
            query_type = "monthly"
            try:
                month_int = int(month)
                if month_int < 1 or month_int > 12:
                    return jsonify(code=40010, message="月份必须在1-12之间"), 400
                query_condition["month"] = month_int
            except ValueError:
                return jsonify(code=40010, message="月份必须为整数"), 400
        
        if day and month:  # 日期查询需要同时有月份
            query_type = "daily"
            try:
                day_int = int(day)
                if day_int < 1 or day_int > 31:
                    return jsonify(code=40010, message="日期必须在1-31之间"), 400
                query_condition["day"] = day_int
            except ValueError:
                return jsonify(code=40010, message="日期必须为整数"), 400
        
        # 根据查询类型选择集合
        collection_name = ""
        if query_type == "yearly":
            collection_name = Config.MONGODB_COLLECTIONS["yearly_duration"]
        elif query_type == "monthly":
            collection_name = Config.MONGODB_COLLECTIONS["monthly_duration"]
        else:  # daily
            collection_name = Config.MONGODB_COLLECTIONS["daily_duration"]
        
        # 记录查询条件和集合名称，便于调试
        print(f"[DEBUG] 查询条件: {query_condition}, 集合: {collection_name}")
        
        # 从MongoDB获取用户听歌时长数据
        duration_records = []
        with mongo_collection(collection_name) as collection:
            # 查询数据
            duration_records = list(collection.find(query_condition))
            
            # 如果没有找到数据，尝试从listen_records集合聚合
            if not duration_records:
                print(f"[DEBUG] 在{collection_name}中未找到数据，尝试从listen_records中聚合")
                
                # 构建日期条件
                date_condition = {"$or": [{"user_id": user_id_int}, {"user_id": user_id}]}
                
                if year:
                    if query_type == "yearly":
                        # 年度查询：匹配整年
                        date_condition["date"] = {"$regex": f"^{year_int}"}
                    elif query_type == "monthly":
                        # 月度查询：匹配年月
                        month_str = f"{month_int:02d}"
                        date_condition["date"] = {"$regex": f"^{year_int}-{month_str}"}
                    elif query_type == "daily":
                        # 日度查询：匹配具体日期
                        month_str = f"{month_int:02d}"
                        day_str = f"{day_int:02d}"
                        date_condition["date"] = f"{year_int}-{month_str}-{day_str}"
                
                with mongo_collection(Config.MONGODB_COLLECTIONS["listen_records"]) as records_collection:
                    listen_records = list(records_collection.find(date_condition))
                    
                    if listen_records:
                        # 手动聚合数据
                        total_duration = 0
                        daily_stats = {}
                        
                        for record in listen_records:
                            # 累加听歌时长
                            if "duration" in record:
                                duration = record.get("duration", 0)
                                total_duration += duration
                                
                                # 如果有日期信息，按日期统计
                                if "date" in record:
                                    date = record["date"]
                                    if date not in daily_stats:
                                        daily_stats[date] = 0
                                    daily_stats[date] += duration
                        
                        # 创建聚合记录
                        aggregated_record = {
                            "user_id": user_id_int,
                            "timestamp": datetime.now(),
                            "total_duration": total_duration,  # 总时长（分钟）
                            "daily_stats": daily_stats if daily_stats else None  # 按日期统计的时长
                        }
                        
                        # 添加年月日信息
                        if year:
                            aggregated_record["year"] = year_int
                        if month:
                            aggregated_record["month"] = month_int
                        if day:
                            aggregated_record["day"] = day_int
                        
                        duration_records = [aggregated_record]
        
        # 如果仍然没有数据，返回空结果
        if not duration_records:
            return jsonify({
                "code": 0,
                "message": "未找到用户听歌时长数据",
                "user_id": user_id_int,
                "query_type": query_type,
                "data": []
            }), 200
        
        for record in duration_records:
            if "_id" in record:
                del record["_id"]
            
            # 格式化时间戳
            if "timestamp" in record and isinstance(record["timestamp"], datetime):
                record["timestamp"] = record["timestamp"].isoformat()
        
        # 构建响应
        response = {
            "code": 0,
            "message": "获取用户听歌时长数据成功",
            "user_id": user_id_int,
            "query_type": query_type,
            "data": duration_records
        }
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取用户听歌时长异常: {str(e)}")
        import traceback
        traceback.print_exc()  # 打印完整堆栈跟踪
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@general_bp.route('/v1/get_period_stats', methods=['GET'])
def get_period_stats():
    """
    获取用户听歌时段分布接口
    请求示例：/api/v1/get_period_stats?user_id=4&year=2025&month=4&day=
    
    参数说明：
    - user_id: 用户ID (必填)
    - year: 年份 (选填，默认当前年)
    - month: 月份 (选填，如果提供则返回月度数据)
    - day: 日期 (选填，如果提供则返回日度数据)
    
    根据参数组合返回不同粒度的数据:
    - 只有year: 返回年度数据
    - year+month: 返回月度数据
    - year+month+day: 返回日度数据
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        year = request.args.get('year')
        month = request.args.get('month')
        day = request.args.get('day')
        
        # 参数验证
        if not user_id:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message="缺少必要参数: user_id"
            ), 400
            
        if not validate_user_id(user_id):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
        
        # 转换用户ID为整数类型
        user_id_int = int(user_id)
        
        # 确定查询类型和构建查询条件
        query_type = "yearly"
        query_condition = {}
        
        # 添加用户ID条件 - 同时支持字符串和整数类型
        query_condition["$or"] = [{"user_id": user_id_int}, {"user_id": user_id}]
        
        # 设置当前年份作为默认值
        current_year = datetime.now().year
        year_int = current_year
        
        if year:
            try:
                year_int = int(year)
                query_condition["year"] = year_int
            except ValueError:
                return jsonify(code=40010, message="年份必须为整数"), 400
        else:
            # 如果未提供年份，使用当前年份
            query_condition["year"] = current_year
        
        if month:
            query_type = "monthly"
            try:
                month_int = int(month)
                if month_int < 1 or month_int > 12:
                    return jsonify(code=40010, message="月份必须在1-12之间"), 400
                query_condition["month"] = month_int
            except ValueError:
                return jsonify(code=40010, message="月份必须为整数"), 400
        
        if day and month:  # 日期查询需要同时有月份
            query_type = "daily"
            try:
                day_int = int(day)
                if day_int < 1 or day_int > 31:
                    return jsonify(code=40010, message="日期必须在1-31之间"), 400
                query_condition["day"] = day_int
            except ValueError:
                return jsonify(code=40010, message="日期必须为整数"), 400
        
        # 根据查询类型选择集合
        collection_name = ""
        if query_type == "yearly":
            collection_name = Config.MONGODB_COLLECTIONS["yearly_period_stats"]
        elif query_type == "monthly":
            collection_name = Config.MONGODB_COLLECTIONS["monthly_period_stats"]
        else:  # daily
            collection_name = Config.MONGODB_COLLECTIONS["daily_period_stats"]
        
        # 记录查询条件和集合名称，便于调试
        print(f"[DEBUG] 查询条件: {query_condition}, 集合: {collection_name}")
        
        # 从MongoDB获取用户听歌时段分布数据
        period_stats = []
        with mongo_collection(collection_name) as collection:
            # 查询数据
            period_stats = list(collection.find(query_condition))
            
            # 如果没有找到数据，尝试从listen_records集合聚合
            if not period_stats:
                print(f"[DEBUG] 在{collection_name}中未找到数据，尝试从listen_records中聚合")
                
                # 构建日期条件
                date_condition = {"$or": [{"user_id": user_id_int}, {"user_id": user_id}]}
                
                if year:
                    if query_type == "yearly":
                        # 年度查询：匹配整年
                        date_condition["date"] = {"$regex": f"^{year_int}"}
                    elif query_type == "monthly":
                        # 月度查询：匹配年月
                        month_str = f"{month_int:02d}"
                        date_condition["date"] = {"$regex": f"^{year_int}-{month_str}"}
                    elif query_type == "daily":
                        # 日度查询：匹配具体日期
                        month_str = f"{month_int:02d}"
                        day_str = f"{day_int:02d}"
                        date_condition["date"] = f"{year_int}-{month_str}-{day_str}"
                
                with mongo_collection(Config.MONGODB_COLLECTIONS["listen_records"]) as records_collection:
                    listen_records = list(records_collection.find(date_condition))
                    
                    if listen_records:
                        # 手动聚合数据
                        period_distribution = {
                            "morning": 0,    # 6:00-12:00
                            "afternoon": 0,  # 12:00-18:00
                            "evening": 0,    # 18:00-24:00
                            "night": 0       # 0:00-6:00
                        }
                        
                        # 添加调试日志
                        print(f"[DEBUG] 找到 {len(listen_records)} 条听歌记录")
                        
                        for record in listen_records:
                            # 获取时间段信息
                            if "timestamp" in record:
                                # 优先使用timestamp字段
                                timestamp = record.get("timestamp")
                                if isinstance(timestamp, datetime):
                                    hour = timestamp.hour
                                    
                                    # 累加对应时段的时长
                                    duration = record.get("duration", 0)
                                    
                                    # 添加调试日志
                                    print(f"[DEBUG] 记录时间: {timestamp}, 小时: {hour}, 时长: {duration}")
                                    
                                    if 6 <= hour < 12:
                                        period_distribution["morning"] += duration
                                    elif 12 <= hour < 18:
                                        period_distribution["afternoon"] += duration
                                    elif 18 <= hour < 24:
                                        period_distribution["evening"] += duration
                                    else:  # 0 <= hour < 6
                                        period_distribution["night"] += duration
                            elif "time" in record:
                                # 如果没有timestamp字段，尝试使用time字段
                                time_str = record.get("time", "")
                                try:
                                    # 假设时间格式为 "HH:MM:SS" 或 "HH:MM"
                                    hour = int(time_str.split(":")[0])
                                    
                                    # 累加对应时段的时长
                                    duration = record.get("duration", 0)
                                    
                                    # 添加调试日志
                                    print(f"[DEBUG] 记录时间字符串: {time_str}, 小时: {hour}, 时长: {duration}")
                                    
                                    if 6 <= hour < 12:
                                        period_distribution["morning"] += duration
                                    elif 12 <= hour < 18:
                                        period_distribution["afternoon"] += duration
                                    elif 18 <= hour < 24:
                                        period_distribution["evening"] += duration
                                    else:  # 0 <= hour < 6
                                        period_distribution["night"] += duration
                                except (ValueError, IndexError) as e:
                                    # 时间格式解析错误，记录错误并跳过此记录
                                    print(f"[ERROR] 时间格式解析错误: {time_str}, 错误: {str(e)}")
                                    continue
                            elif "period" in record:
                                # 如果有直接的period字段，直接使用
                                period = record.get("period")
                                duration = record.get("duration", 0)
                                
                                # 添加调试日志
                                print(f"[DEBUG] 直接使用period字段: {period}, 时长: {duration}")
                                
                                if period in period_distribution:
                                    period_distribution[period] += duration
                        
                        # 添加调试日志
                        print(f"[DEBUG] 聚合后的时段分布: {period_distribution}")
        
                        # 创建聚合记录
                        aggregated_record = {
                            "user_id": user_id_int,
                            "timestamp": datetime.now(),
                            "period_distribution": period_distribution,
                            "total_duration": sum(period_distribution.values())
                        }
                        
                        # 添加年月日信息
                        if year:
                            aggregated_record["year"] = year_int
                        if month:
                            aggregated_record["month"] = month_int
                        if day:
                            aggregated_record["day"] = day_int
                        
                        period_stats = [aggregated_record]
        
        # 如果仍然没有数据，返回空结果
        if not period_stats:
            return jsonify({
                "code": 0,
                "message": "未找到用户听歌时段分布数据",
                "user_id": user_id_int,
                "query_type": query_type,
                "data": []
            }), 200
        
        for stat in period_stats:
            if "_id" in stat:
                del stat["_id"]
            
            # 格式化时间戳
            if "timestamp" in stat and isinstance(stat["timestamp"], datetime):
                stat["timestamp"] = stat["timestamp"].isoformat()
        
        # 构建响应
        response = {
            "code": 0,
            "message": "获取用户听歌时段分布数据成功",
            "user_id": user_id_int,
            "query_type": query_type,
            "data": period_stats
        }
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取用户听歌时段分布异常: {str(e)}")
        import traceback
        traceback.print_exc()  # 打印完整堆栈跟踪
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500